<?php


namespace app\admin\controller;

use app\common\controller\AdminBaseController;
use app\common\model\tang\Cost as CostModel;
use app\common\model\tang\FloorConfig;
use app\common\model\tang\FormatsConfig;
use app\common\model\tang\MerchantMoney;
use app\common\model\tang\MonthElectricityDegree;
use app\common\model\tang\MonthElectricityRecord;
use app\common\model\tang\MonthSoleElectricityLog;
use think\facade\Db;
use app\common\model\tang\Merchant;

class ElectricityBill extends AdminBaseController
{
    protected function initialize()
    {
        parent::initialize(); // TODO: Change the autogenerated stub
        $this->model = new CostModel();
    }

    //电费账单列表
    public function index()
    {
        if (IS_AJAX) {
            return $this->model->getAdminPageData($this->param, 'id desc', ['type' => 4]);
        }
        $merchant_list = getMerchant();
        //获取菜单列表
        $this->assign(compact("merchant_list"));
        return $this->fetch();
    }

    public function export()
    {
        $this->model->getExportPageData($this->param, 'id desc', ['type' => 4]);
    }

    /**
     * 生成费用单
     */
    public function add()
    {
        $param = $this->param;

        $model = new CostModel();
        $info = Db::name('cost_type')->where('type', 4)->order('create_time DESC')->find();
        if (IS_AJAX) {
            if (empty($param['merchant_id']) && !isset($param['all']) && !isset($param['activities']) && !isset($param['lcName'])) {
                return self::ajaxResult([], 0, -1, '请至少选择一项');
            }
            $MerchantModel = new Merchant();
            //根据传递过来的商户数组,进行计算并进入cost表中
            if ($param['type'] == 2) {
                Db::startTrans();
                try {
                    if (isset($param['all'])) {
                        $listInfo = MonthSoleElectricityLog::field('merchant_id')->where('status', 0)->column('merchant_id');
                        $param['merchant_id'] = array_values(array_unique($listInfo));
                    }
                    $ids = session('merchant_id');
                    if (isset($ids)) {
                        $param['merchant_id'] = $ids;
                        $param['merchant_id'] = explode(',', $param['merchant_id']);
                    }
                    if (!empty($param['activities'])) {
                        $param['merchant_id'] = Merchant::where('activities', $param['activities'])->column('id');
                    }
                    if (!empty($param['lcName'])) {
                        $param['merchant_id'] = Merchant::where('lcName', $param['lcName'])->column('id');
                    }
                    if (!empty($param['lcName']) && !empty($param['activities'])) {
                        $param['merchant_id'] = Merchant::where(['lcName' => $param['lcName'], 'activities' => $param['activities']])->column('id');
                    }
                    $electrity = [];
                    if ($param['merchant_id']) {
                        foreach ($param['merchant_id'] as $key => $val) {
                            //查出用户所拥有的正在使用水表
                            $res = $MerchantModel::alias('m')
                                ->join('tang_month_sole_electricity_log r', 'm.id=r.merchant_id', 'LEFT')
                                ->join('tang_watch_maintain w', "w.pointId = r.pointId", 'LEFT')
                                ->where([
                                    'm.id' => intval($val),
                                    'r.dataTime' => $param['start_time'],
                                    'r.status' => 0,
                                    'w.status' => 1,

                                ])
                                ->where('r.merchant_id', '<>', 0)
                                ->where('r.merchant_id', '<>', 1918)
                                ->field('m.id,m.merchant_sn,m.name,m.code,w.initial_degrees,r.id as r_id,r.merchant_id,r.userId,r.pointId,r.pointName,r.dataTime,
            r.rate,r.percent,r.totalMoney,r.totalPower,r.zongEnd,r.zongMoney,r.zongPower,r.zongStart')
                                ->select()->toArray();
                            //循环查出来用户的数据,并进行计算获取用户的需要交纳的费用
                            $allMoney = 0;//总金额
                            $allElectricity = 0;//总电量
                            $jiMoney = 0;//对账金额
                            foreach ($res as $k => $v) {
                                //修改电费单价,防止每月电费单价不同
                                MonthSoleElectricityLog::where('id', $v['r_id'])->update([
                                    'price' => $param['price'],
                                    'status' => 1,
                                    'update_time' => time(),
                                    'rate' => $v['rate']
                                ]);
                                $result = handWritten($v, $param['price']); //手抄表计算
                                $allElectricity += $result['allElectricity'];
                                //计算金额,电量*单价*倍率
                                $allMoney = $result['allMoney'];
                                $jiMoney = $result['jiMoney'];

                                $allMoney = sprintf('%01.2f', $allMoney);
                                $jiMoney = sprintf('%01.4f', $jiMoney);
                                $allElectricity = sprintf('%01.2f', $allElectricity);
                                $TaxMoneyArr = [
                                    'tax_money' => 0, // 税率金额
                                    'money' => $allMoney * 100,
                                    'z_money' => $allMoney * 100,
                                ];

                                $data['order_sn'] = OrderSn();
                                $data['type'] = 4;
                                $data['merchant_id'] = $val;
                                $data['cost_type_id'] = 45;
//                            $data['pay_status'] = 0; //0未支付1已支付 -1已级退费
                                $data['pay_status'] = 1; //0未支付1已支付 -1已级退费
                                $data['pay_time'] = $param['start_time'] . '-01 12:12:12';
                                $data['all_amount'] = $allMoney * 100;
                                $data['amount'] = $allMoney * 100;
                                $data['electric_money'] = $allMoney * 100;
                                $data['pay_amount'] = $allMoney * 100;
                                $data['pointId'] = $v['pointId'];
//                            $data['fuwu_money']=sprintf('%01.2f', $result['tMoney'])*100;
                                $data['reconciliation_amount'] = $jiMoney * 10000;//对账用4位截取
                                $data['real_amount'] = $allMoney * 100;
                                $data['service_charge'] = 0;
                                $data['unit_price'] = isset($param['price']) ? $param['price'] : 0;//交费单价
                                $data['date_type'] = 2;//1时间区间2长期有效
                                $data['electrity_type'] = 2;//1费率用电2单一用电
                                $data['use_number'] = $allElectricity;//用电总量
                                $data['is_admin_create'] = 1;//是否为人工创建1人工
                                $data['create_time'] = strtotime("first day of next month", strtotime($v['dataTime']));;
                                $data['start_time'] = strtotime($v['dataTime']);
                                $data['end_time'] = strtotime(date("Y-m-t", strtotime($v['dataTime'])));
                                $data['settlement_time'] = $param['start_time'];
                                $data['contract_code'] = $v['code'];
                                $data['department_id'] = 6;//部门ID
                                upMerchantBalance($val,$allMoney*100);
                                $electrity[] = $data;
                            }
                        }
                        $model->insertAll($electrity);
                    } else {
                        return self::ajaxResult([], 0, -1, '商户选择有误');
                    }
                    Db::commit();
                    return self::ajaxResult([], 0, 1, '订单生成成功');
                } catch (\Exception $exception) {
                    Db::rollback();
                    return self::JsonReturn($exception->getMessage(), 0);
                }
            } else {
                //费率用电计算
                if (isset($param['all'])) {
                    $listInfo = MonthElectricityDegree::field('merchant_id')->where('status', 0)->column('merchant_id');
                    $param['merchant_id'] = array_values(array_unique($listInfo));
                }
                $ids = session('merchant_id');
                if (isset($ids)) {
                    $param['merchant_id'] = $ids;
                    $param['merchant_id'] = explode(',', $param['merchant_id']);
                }
                if (!empty($param['activities'])) {
                    $param['merchant_id'] = Merchant::where('activities', $param['activities'])->column('id');
                }
                if (!empty($param['lcName'])) {
                    $param['merchant_id'] = Merchant::where('lcName', $param['lcName'])->column('id');
                }
                if (!empty($param['lcName']) && !empty($param['activities'])) {
                    $param['merchant_id'] = Merchant::where(['lcName' => $param['lcName'], 'activities' => $param['activities']])->column('id');
                }
                //同样需要循环出来找出多商户的多电表
                Db::startTrans();
                try {
                    $electrity = [];
                    foreach ($param['merchant_id'] as $key => $val) {
                        //查出用户所拥有的正在使用电表
                        $res = $MerchantModel::alias('m')
                            ->where([
                                'm.id' => intval($val),
                                'r.dataTime' => $param['start_time'],
                                'r.status' => 0,
                                'w.type' => 1,
                                'w.status' => 1
                            ])
                            ->where('r.merchant_id', '<>', 0)
                            ->where('r.merchant_id', '<>', 1918)
                            ->join('tang_month_electricity_degree r', 'm.id=r.merchant_id', 'LEFT')
                            ->join('tang_watch_maintain w', "r.pointId = w.pointId", 'LEFT')
                            ->field('m.id,m.merchant_sn,m.name,m.code,r.rate,w.initial_degrees,w.pointName,r.id as r_id,r.dataTime,r.fengStart,r.fengEnd,r.guStart,r.guEnd,r.pingStart,r.pingEnd,r.pointId')
                            ->select()->toArray();
                        //循环查出来用户的数据,并进行计算获取用户的需要交纳的费用
                        $allMoney = 0;//总金额
                        $allElectricity = 0;//总电量
                        $jiMoney = 0; //对账money
                        foreach ($res as $k => $v) {
                            //修改电费单价,防止每月电费单价不同
                            $result = rate($v, $param); //计算费率用电
                            $allElectricity = $result['allElectricity'];
                            $jiMoney = $result['jiMoney'];
                            $allMoney = $result['allMoney'];
                            MonthElectricityDegree::where('id', $v['r_id'])->update([
//                                'fMoney' => bcmul($param['fmoney'], (1 + $param['add_price'] / 100), 4),
//                                'gMoney' => bcmul($param['gmoney'], (1 + $param['add_price'] / 100), 4),
//                                'pMoney' => bcmul($param['pmoney'], (1 + $param['add_price'] / 100), 4),
//                                'tMoney' => bcmul($param['tmoney'], (1 + $param['add_price'] / 100), 4),
                                'fMoney' => $param['fmoney'],
                                'gMoney' => $param['gmoney'],
                                'pMoney' => $param['pmoney'],
                                'tMoney' => $param['tmoney'],
                                'status' => 1,
                                'update_time' => time(),
                                'rate' => $v['rate']
                            ]);
                            $allMoney = sprintf('%01.2f', $allMoney);
                            $jiMoney = sprintf('%01.4f', $jiMoney);
                            $allElectricity = sprintf('%01.2f', $allElectricity);
                            //计算结果保留两位小数
//                        if ($info['tax'] == 1) {
//                            $TaxMoneyArr = TaxMoney($allMoney * 100, 1, $info['tax_rate']);
//                        } else {
//                            $TaxMoneyArr = [
//                                'tax_money' => 0, // 税率金额
//                                'money' => $allMoney * 100,
//                                'z_money' => $allMoney * 100,
//                            ];
//                        }
                            $data['order_sn'] = OrderSn();
                            $data['electric_money'] = sprintf('%01.2f', $result['subtotal']) * 100;
                            $data['fuwu_money'] = sprintf('%01.2f', $result['tMoney']) * 100;
                            $data['pointId'] = $v['pointId'];
                            $data['add_price'] = $param['add_price'];
                            $data['type'] = 4;
                            $data['merchant_id'] = $val;
                            $data['cost_type_id'] = 45;
//                            $data['pay_status'] = 0; //0未支付1已支付 -1已级退费
                            $data['pay_status'] = 1; //0未支付1已支付 -1已级退费
                            $data['pay_time'] = $param['start_time'] . '-01 12:12:12';
                            $data['amount'] = $allMoney * 100;
                            $data['all_amount'] = $allMoney * 100;
                            $data['reconciliation_amount'] = $jiMoney * 10000;//对账用4位截取
                            $data['real_amount'] = $allMoney * 100;
                            $data['pay_amount'] = $allMoney * 100;
                            $data['service_charge'] = 0;
                            $data['unit_price'] = isset($param['price']) ? $param['price'] : 0;//交费单价
                            $data['date_type'] = 2;//1时间区间2长期有效
                            $data['electrity_type'] = 1;//1费率用电2单一用电
                            $data['use_number'] = $allElectricity;//用电总量
                            $data['is_admin_create'] = 1;//是否为人工创建1人工
                            $data['create_time'] = strtotime("first day of next month", strtotime($v['dataTime']));
                            $data['start_time'] = strtotime($v['dataTime']);
                            $data['contract_code'] = $v['code'];
                            $data['end_time'] = strtotime(date("Y-m-t", strtotime($v['dataTime'])));
                            $data['settlement_time'] = $param['start_time'];
                            $data['department_id'] = 6;//部门ID
                            if ($allMoney > 0) {//停用的电表不生成订单
                                upMerchantBalance($val,$allMoney*100); //重新计算商户余额
                                $electrity[] = $data;
                            }
                        }
                    }
                    $model->insertAll($electrity);
                    Db::commit();
                    return self::ajaxResult([], 0, 1, '订单生成成功');
                } catch (\Exception $exception) {
                    Db::rollback();
                    return self::JsonReturn($exception->getMessage(), 0);
                }
            }
        }
        $merchant_list = getMerchant();
        $money = (new MerchantMoney())->where(['dateTime' => date('Y-m', strtotime('-1 month'))])->find();
        $activities = (new FormatsConfig())->select();
        $lcName = (new FloorConfig())->select();
        //获取菜单列表
        if (empty($money)) {
            $money = [
                'linmoney' => NUll,
                'fmoney' => NUll,
                'gmoney' => NUll,
                'pmoney' => NUll,
                'tmoney' => NUll,
                'stmoney' => NUll,
            ];
        }
        //获取菜单列表
        $this->assign(compact("merchant_list", "money", "activities", "lcName"));
        //获取设置的电费
//        $this->assign('cost_money', $info['cost_money']);
        return $this->fetch();
    }

    /**
     * 根据时间和type值查询对应的商户预信息
     */
    public function getList()
    {
        $param = $this->param;
        //选择当前月份直接返回失败
//        if (strtotime($param['month']) == strtotime(date('Y-m', time()))) {
//            return self::ajaxResult([], 0, 1, '不能选择当前月份');
//        }
        if ($param['type'] == 1) { //费率用电,找出所有未核算的商户
            $MerchantModel = new Merchant();
            $result = $MerchantModel->getMonthDegree($param, '', [], $param['month']);
        } else {
            $MerchantModel = new Merchant();
            $result = $MerchantModel->getMonthRecord($param, '', [], $param['month']);
        }
        return $result;
    }

    /**
     * 查看订单详情
     */
    public function detail()
    {
        $param = $this->param;
        if ($param['type'] == 1) { //费率用电
            $list = [
                'settlement_time' => $param['settlement_time'],
                'merchant_id' => $param['merchant_id'],
                'pointId' => $param['pointId'],
            ];
            $newArray = rateElectricity($list);
            $this->assign('list', $newArray);
        } else { //单一用电
            //查找用户对应表的记录
            $info = MonthSoleElectricityLog::alias('r')
                ->leftjoin('tang_watch_maintain w', 'r.pointId=w.pointId')
                ->leftjoin('tang_merchant t', 't.id=r.merchant_id')
                ->where([
                    'r.dataTime' => $param['settlement_time'],
                    'r.pointId' => $param['pointId'],
                    'r.merchant_id' => $param['merchant_id'],
                ])
                ->field('t.id,t.merchant_sn,t.name,w.initial_degrees,r.merchant_id,r.userId,r.pointId,r.pointName,r.dataTime,
            r.rate,r.percent,r.totalMoney,r.totalPower,r.zongEnd,r.zongMoney,r.zongPower,r.zongStart,r.price,r.create_time')
                ->select()->toArray();
            foreach ($info as $key => $val) {
                $result = handWritten($val, $val['price']);
                $info[$key]['electricity'] = sprintf('%01.2f', $result['allElectricity']);
                $info[$key]['money'] = sprintf('%01.2f', $result['allMoney']);
                $info[$key]['dataTime'] = $val['dataTime'];
            }
            $this->assign('list', $info);
        }
        $this->assign('type', $param['type']);

        return $this->fetch();
    }

    /**
     * 开票
     */
    public function invoice()
    {
        $param = $this->request->param();
        $id = intval($param['id']);
        $model = new \app\common\model\tang\Cost();
        $cost = $model->find($id);
        if (empty($cost)) {
            return self::ajaxResult([], 0, 1, '不存在的订单');
        }
        $invoice = empty($cost->invoice) ? 1 : 0;
        $update = $model->update(['invoice' => $invoice], ['id' => $id]);
        if ($update) {
            return self::ajaxResult([], 0, 0, '修改成功');
        } else {
            return self::ajaxResult([], 0, 1, '修改失败');
        }

    }

    /**
     * 删除
     */
    public function del()
    {
        $param = $this->request->param();
        $ids = explode(',',$param['ids']);
        $costInfo = CostModel::where('id','in',$ids)->field('id,pointId,settlement_time,electrity_type')->select();
        foreach ($costInfo as $key=>$value){
            MonthSoleElectricityLog::update(['status'=>0],['dataTime'=>$value['settlement_time'],'pointId'=>$value['pointId']]);
            CostModel::where('id',$value['id'])->delete();
            MonthElectricityDegree::update(['status'=>0],['dataTime'=>$value['settlement_time'],'pointId'=>$value['pointId']]);
        }
        return self::ajaxResult([], 0, 0, '删除成功');
    }

    /**
     * 开票
     */
    public function invoceAll()
    {
        $param = $this->request->param();
        $model = new \app\common\model\tang\Cost();


        $update = $model->whereIn('id', $param['ids'])->update(['invoice' => 1]);
        if ($update) {
            return self::ajaxResult([], 0, 0, '操作成功');
        } else {
            return self::ajaxResult([], 0, 1, '操作失败');
        }

    }
}